package com.funny.stock.config;

import com.alibaba.fastjson.JSON;
import com.funny.stock.base.util.IPUtils;
import com.funny.stock.base.util.ResultUtil;
import com.funny.stock.base.vo.Result;
import com.funny.stock.config.security.UserAuthService;
import com.funny.stock.user.service.SysLoginLogService;
import com.funny.stock.user.service.UserService;
import com.funny.stock.user.util.StockPasswordEncoder;
import com.funny.stock.user.util.UserSecurityUtil;
import com.funny.stock.user.vo.LoginModeEnum;
import com.funny.stock.user.vo.LoginUserInfo;
import com.funny.stock.user.vo.SysUserVO;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
 * @author  pengl
 * @date    2020/4/9
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);


    @Autowired
    UserAuthService userAuthService;

    @Autowired
    UserService userService;

    @Autowired
    SysLoginLogService sysLoginLogService;

//    @Autowired
//    MyFilterSecurityInterceptor myFilterSecurityInterceptor;

//    @Autowired
//    AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/register","/openapi/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin().loginPage(AppConstant.LOGIN_URL)//登录成功后跳转
                .permitAll()
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .failureHandler(this::doAuthenticationFail)
                .successHandler(this::doAuthenticationSuccess);

        http.sessionManagement()
                .maximumSessions(1)
                .maxSessionsPreventsLogin(false)
                .expiredUrl("/login")
                .sessionRegistry(sessionRegistry());


        http.logout()
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                .clearAuthentication(true)//清除权限
                .invalidateHttpSession(true)
                .permitAll().logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    UserSecurityUtil.removeUser();

                    Result result = ResultUtil.success(null);
                    String json = JSON.toJSONString(result);
                    logger.info("logout result:{}",json);

                    UserSecurityUtil.writeResponseResult(httpServletResponse, result);
                });

//        http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);


        http.exceptionHandling()
                .accessDeniedHandler(((request, response, accessDeniedException) -> {
                    Result result = ResultUtil.error(ErrorConstants.FORBIDDEN);

                    UserSecurityUtil.writeResponseResult(response, result);
                }));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userAuthService)
        .passwordEncoder(new StockPasswordEncoder());
    }

    private void doAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        HttpSession session = UserSecurityUtil.getHttpSession();
        String sessionId = session.getId();
        SysUserVO userVO = UserSecurityUtil.getUser();

        LoginUserInfo loginUserInfo = new LoginUserInfo();
        loginUserInfo.setSessionId(sessionId);
        loginUserInfo.setUsername(userVO.getLoginAccount());
        loginUserInfo.setPassword("");
        loginUserInfo.setSessionExpiresIn(UserSecurityUtil.SESSION_VALID_TIME_SECOND);

        sysLoginLogService.saveLoginEvent(loginUserInfo.getUsername(),
                IPUtils.getIpAddr(request), LoginModeEnum.USER_LOGIN.getType());

        Result result = ResultUtil.success(loginUserInfo);
        String json = JSON.toJSONString(result);
        logger.info("result:{}",json);

        UserSecurityUtil.writeResponseResult(response, result);
    }

    private void doAuthenticationFail(HttpServletRequest request,
                                      HttpServletResponse response, AuthenticationException exception){
        UserSecurityUtil.removeUser();
        String defaultMsg = ErrorConstants.PASSWORD_ERROR;

        String requestFailMsg = UserSecurityUtil.getRequestFailMsg();
        if(StringUtils.isEmpty(requestFailMsg)){
            if (exception instanceof BadCredentialsException) {
                requestFailMsg = defaultMsg;
            }
        }

        requestFailMsg = "登录失败，" + requestFailMsg;
        UserSecurityUtil.writeResponseResult(response, ResultUtil.error(requestFailMsg));
    }


    @Bean
    public SessionRegistry sessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        return sessionRegistry;
    }
}
